package com.woyou.ui.activity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;
import org.json.JSONException;
import org.json.JSONObject;

import retrofit.RetrofitError;
import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.woyou.Constant;
import com.woyou.bean.CodeListResult;
import com.woyou.bean.Coupon;
import com.woyou.bean.Info;
import com.woyou.bean.ShopItem;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.MD5Req;
import com.woyou.bean.rpc.ShopListReq;
import com.woyou.service.LocationLoopService;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.adapter.ShopListAdapter;
import com.woyou.ui.api.IBackEventStrategy;
import com.woyou.ui.component.ErrorHintView;
import com.woyou.ui.component.ErrorHintView.OperateListener;
import com.woyou.ui.fragment.ShopsFragment_;
import com.woyou.utils.Utils;

/**
 * 我的优惠券界面MyCouPonFragment
 * 
 * @author tanglc
 */
@EActivity(R.layout.fm_coupon)
public class MyCouPonActivity extends BaseActivity implements IBackEventStrategy{

	@ViewById RelativeLayout myback;
	@ViewById TextView head_title;
	@ViewById(R.id.coupon_webview) WebView mWeb;
	@ViewById(R.id.hintView) ErrorHintView hintView;
	@ViewById(R.id.coupon_jump_shops) RelativeLayout jumpShops; //可选的店铺列表
	@ViewById(R.id.coupon_shop_list) ListView shopList;
	@ViewById(R.id.coupon_close) LinearLayout close; //关闭按钮	
	@ViewById(R.id.jump_shop_ll) LinearLayout markLin; //黑色蒙板区域
	
	private List<ShopItem> shopItems = new ArrayList<ShopItem>();
	private ShopListAdapter shopAdapter;
	private ShopListReq shopListReq = new ShopListReq();
	private int pageNext = 1;
	
	@Override
	public void onResume() {
		super.onResume();
		initView();
	}

	@Click({ R.id.myback })
	void back() { 				
		// 退出设置界面
		backOperate();
	}
	
	@Click({R.id.coupon_close, R.id.jump_shop_ll})
	void closeShops(){
		jumpShops.setVisibility(View.GONE);
	}
	
	class Params {
		public String uId;
		public String sId;
		public String pwd;
		public String lat;
		public String lng;
		public String cityName;
	}
	
	/**
	 * 初始化listview
	 */
	private void initListView() {
		if ( shopAdapter == null ) {
			shopAdapter = new ShopListAdapter(shopItems, mContext);
			shopList.setAdapter(shopAdapter);
		}
	}
	
	/**
	 * 初始化View
	 */
	private void initView() {  
		hintView.loadingData();
		head_title.setText("我的优惠券");
		initListView();
		
		String url = "http://" + Constant.WEB_SERVER + "/ResultMyCoupon2/";
		UserInfo userInfo = mUserModel.getUserInfo();
		Params params = new Params();
		params.uId = userInfo.getuId();
		params.pwd = userInfo.getPwd();
		
		if ( LocationLoopService.getInstance(mContext).getChosenAddr()!=null ) {
			params.lat = LocationLoopService.getInstance(mContext).getChosenAddr().getLat();
			params.lng = LocationLoopService.getInstance(mContext).getChosenAddr().getLng();
			params.cityName = LocationLoopService.getInstance(mContext).getChosenAddr().getCityName();
		}  else {
			if (mBaiduLocationService.getLastLocation() != null) {
				params.lat = mBaiduLocationService.getLastLocation().getLatitude() + "";
				params.lng = mBaiduLocationService.getLastLocation().getLongitude() + "";
				params.cityName = mBaiduLocationService.getLastLocation().getCity();
			}
		}

		MD5Req<Params> req = new MD5Req<Params>(params);
		try {
			url = Utils.getWebUrl(url, req);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		initWebView(url);
	}

	@SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled" })
	private void initWebView(String url) {
		// String url = getIntent().getStringExtra("url");
		// 如果访问的页面中有Javascript，则webview必须设置支持Javascript。
		mWeb.getSettings().setJavaScriptEnabled(true);
		mWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		// 触摸焦点起作用
		mWeb.requestFocus();
		// 取消滚动条
		mWeb.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		// 设置WevView要显示的网页：
		mWeb.loadUrl(url);
		// // 设置字体大小
		// if (ParseUtils.getSDKVersionNumber() >= 14) {
		// mWeb.getSettings().setTextZoom(35);
		// } else {
		// mWeb.getSettings().setTextSize(TextSize.SMALLEST);
		// }
		// 设置不可缩放
		mWeb.getSettings().setSupportZoom(false);
		mWeb.getSettings().setBuiltInZoomControls(false);

		mWeb.setWebViewClient(new MyWebViewClient());
		mWeb.setWebChromeClient(new WebChromeClient());
		mWeb.addJavascriptInterface(this, "ideliver");
	}

	class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (!TextUtils.isEmpty(url)) {
				mWeb.loadUrl(url);
			}
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			hintView.hideLoading();
			String title = view.getTitle();
			if (TextUtils.isEmpty(title)) {
				return;
			}

			if (!title.contains("ideliver")) {
				if( !NetWorkCenter.isNetworkConnected(mContext) ){
					hintView.netError(new OperateListener() {
						@Override
						public void operate() {
							initView();
						}
					});
				}else{
					hintView.loadFailure(new OperateListener() {
						@Override
						public void operate() {
							initView();
						}
					});
				}
				
			}
		}
		
		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			if (NetWorkCenter.isNetworkConnected(mContext)) {
				hintView.loadFailure(new OperateListener() {
					@Override
					public void operate() {
						initView();
					}
				});
			} else {
				hintView.netError(new OperateListener() {
					@Override
					public void operate() {
						initView();
					}
				});
			}
		}
	}

	@SuppressWarnings("rawtypes")
	public void messageFromJS(String message) {
		try {
			JSONObject msg = new JSONObject(message);
			String type = msg.getString("messageType");
			if ("selectCoupon".equals(type)) {

				String list = msg.getString("params");
				Gson gson = new Gson();
				List<Coupon> coupons = gson.fromJson(list, new TypeToken<List<Coupon>>(){}.getType());
				if (coupons != null && coupons.size() > 0) {
					int size = coupons.size();
					for (int i = 0; i < size; i++) {
						Coupon coupon = coupons.get(i);
						List<String> codeList = coupon.getsIdList();
						if (codeList == null) {
							codeList = new ArrayList<String>();
						}
						shopItems.clear();
						pageNext = 1;
						loadShopList(codeList);
					}
				} else if ("tryAgain".equals(type)) {
					showProgressDialog();
					mBaiduLocationService.startLocation();
					
				} else if ("browseShops".equals(type)) {
					Info<Class> info = new Info<Class>();
					info.setData(ShopsFragment_.class);
					openActivity(HomeActivity_.class, info);
					
				} else {
					showToast("选择优惠券失败!");
				}
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 加载店铺列表
	 */
	@Background void loadShopList(List<String> codeList){
		showProgressDialog();
		CodeListResult<ShopItem> result = null;
		int size = codeList.size();
		
		if ( pageNext==0 ) {
			dismissProgressDialog();
			return;
		}
		
		try {
			if ( LocationLoopService.getInstance(mContext).getChosenAddr()!=null ) {
				shopListReq.setLat(LocationLoopService.getInstance(mContext).getChosenAddr().getLat());
				shopListReq.setLng(LocationLoopService.getInstance(mContext).getChosenAddr().getLng());
			}  else {
				if (mBaiduLocationService.getLastLocation() != null) {
					shopListReq.setLat(mBaiduLocationService.getLastLocation().getLatitude() + "");
					shopListReq.setLng(mBaiduLocationService.getLastLocation().getLongitude() + "");
				}
			}
			shopListReq.setuId("");
			shopListReq.setKey("");
			shopListReq.setScope(""); 										//店铺类型
			shopListReq.setSortType(""); 									//排序字段 1-按照距离 2-起送价最低 3-销量最高
			shopListReq.setPage(pageNext); 									// 页号
			shopListReq.setCodeList(codeList.toArray(new String[size])); 	//店铺编号列表
//			String[] str = new String[]{"SHDP014", "SHDP013", "SHDP015", "SHDP010", "SHDP016", "SHDP008"};
//			shopListReq.setCodeList(str);
			result = mShopsModel.v2_3queryShopList(shopListReq);
			if (result != null && result.code == 1) {
				refreshUI(result);
			}
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case HTTP:
				break;
			case CONVERSION:
				break;
			case NETWORK:
				break;
			case UNEXPECTED:
				break;
			}
		} finally{
			dismissProgressDialog();
		}
		
	}
	
	@ItemClick(R.id.coupon_shop_list)
	public void shopListItemClick(int position) {
		ShopItem shopItem = shopItems.get(position);
		Info<ShopItem> info = new Info<ShopItem>(shopItem);
		info.setOrigin(MyCouPonActivity_.class);
		openActivity(ShopInfoActivity.class, info);
		
		jumpShops.setVisibility(View.GONE);
	}
	
	private void refreshUI(final CodeListResult<ShopItem> result) {
		runOnUI(new Runnable() {
			
			@Override
			public void run() {
				List<ShopItem> list = result.getList();
				if (list == null || list.size() == 0) {
					// 没有数据返回
					shopItems.clear();
					shopAdapter.notifyDataSetChanged();
				} else {
					pageNext = result.page;
					shopItems.addAll(list);
					shopAdapter.notifyDataSetChanged();
					jumpShops.setVisibility(View.VISIBLE);
					shopList.setSelection(0);
				}
			}
		});
	}

	@Override
	public boolean backOperate() {
		if ( jumpShops.getVisibility()==View.VISIBLE ) {
			jumpShops.setVisibility(View.GONE);
			return true;
		} else {
			finish();
			return true;
		}
	}
	

}
